const { list, add, find } = require('./data/org-units')
const { findUser } = require('./data/user')
const { list: listUserRoles } = require('./data/user-roles')
const Mock = require('mockjs')

const base = '/userserver'

module.exports = [{
  url: `${base}/orgUnits`,
  type: 'post',
  response: config => {
    const token = config.headers.authorization.substr('Bearer '.length)
    const u = findUser(token)
    add(config.body, u ? u.orgUnitId : 0)
    return { success: true }
  }
}, {
  url: `${base}/orgUnits/total`,
  type: 'get',
  response: config => {
    return { success: true, data: Mock.Random.integer(800, 1000) }
  }
}, {
  url: `${base}/orgUnits/mine`,
  type: 'get',
  response: config => {
    const token = config.headers.authorization.substr('Bearer '.length)
    const u = findUser(token)
    if (u) {
      const orgUnitIds = Array.from(new Set(listUserRoles(u.id).map(ur => ur.orgUnitId)))
      const ret = []
      for (let i = 0; i < orgUnitIds.length; ++i) {
        const o = find(orgUnitIds[i])
        if (o) {
          ret.push(o)
        }
      }
      return { success: true, data: ret }
    }
    return { success: false, message: '用户未找到' }
  }
}, {
  url: `${base}/orgUnits`,
  type: 'get',
  response: config => {
    const { page, limit, type, name } = config.query
    return list(page, limit, type, name)
  }
}, {
  url: `${base}/orgUnits/current/[1-9][0-9]*`,
  type: 'put',
  response: config => {
    const id = config.url.match(/[1-9][0-9]*/)
    const token = config.headers.authorization.substr('Bearer '.length)
    const u = findUser(token)
    if (u) {
      u.orgUnitId = id
      return { success: true }
    } else {
      return { success: false, message: '用户不存在' }
    }
  }
}, {
  url: `${base}/orgUnits/[1-9][0-9]*/online`,
  type: 'put',
  response: config => {
    const id = config.url.match(/[1-9][0-9]*/)
    const orgUnit = find(id)
    if (orgUnit) {
      orgUnit.status = 0
      return { success: true }
    } else {
      return { success: false, message: '店铺不存在' }
    }
  }
}, {
  url: `${base}/orgUnits/[1-9][0-9]*/offline`,
  type: 'put',
  response: config => {
    const id = config.url.match(/[1-9][0-9]*/)
    const orgUnit = find(id)
    if (orgUnit) {
      orgUnit.status = 1
      return { success: true }
    } else {
      return { success: false, message: '店铺不存在' }
    }
  }
}, {
  url: `${base}/orgUnits/[1-9][0-9]*`,
  type: 'put',
  response: config => {
    const id = config.url.match(/[1-9][0-9]*/)
    const orgUnit = find(id)
    if (orgUnit) {
      const { name, address, hideCloudMovie } = config.body
      orgUnit.name = name
      orgUnit.address = address
      orgUnit.hideCloudMovie = hideCloudMovie
      return { success: true }
    } else {
      return { success: false, message: '记录不存在' }
    }
  }
}]
